package com.easylinkin.linkappapi.lobar.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.async.AsyncUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.lobar.dto.GroupDTO;
import com.easylinkin.linkappapi.lobar.dto.UserProjectDTO;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDTO;
import com.easylinkin.linkappapi.lobar.entity.Group;
import com.easylinkin.linkappapi.lobar.service.GroupService;
import com.easylinkin.linkappapi.lobar.vo.LaborCompanyGroupVo;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogOperateType;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * @author: kan yuanfeng
 * @Date: 2020/11/04 11:42
 * @Description: 项目班组管理
 */
@RestController
@RequestMapping("group")
@Api(tags = "项目班组管理")
public class GroupController {
  
  @Autowired
  private GroupService groupService;
  @Autowired
  private LinkappUserContextProducer linkappUserContextProducer;

  /**
   * @Description: 增加班组
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping
  @ApiOperation("增加班组")
  public RestMessage insert(@RequestBody Group Group){
    //todo 参数验证
    groupService.insert(Group);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 删除班组（包含批量删除）
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @DeleteMapping
  @ApiOperation("删除班组（包含批量删除）")
  @CommonOperateLogAnnotate(module = LogModule.LABOR_MANAGEMENT, desc = "")
  public RestMessage delBatch(@RequestBody Group Group){
    Assert.notEmpty(Group.getIds(),"id不能为空");
    // 记录日志详情
    List<String> groupNames = new ArrayList<>();
    Group.getIds().forEach(p->{
      Group g = groupService.getById(p);
      groupNames.add(g.getName());
    });
    if(CollectionUtil.isNotEmpty(groupNames)){
      LogHelper.setContent(LogOperateType.LABOL_GROUP_DELETE, StringUtil.join(groupNames,","));
    }
    groupService.delBatch(Group.getIds());
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 编辑班组
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping
  @ApiOperation("编辑班组")
  public RestMessage updateById(@RequestBody Group Group){
    Assert.notNull(Group.getId(),"id不能为空");
    groupService.updateOne(Group);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 进退场
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PutMapping("status")
  @ApiOperation("进退场")
  @CommonOperateLogAnnotate(module = LogModule.LABOR_MANAGEMENT, desc = "")
  public RestMessage updateStatus(@RequestBody Group Group){
    Assert.notNull(Group.getId(),"id不能为空");
    // 记录日志详情
    Group g = groupService.getById(Group.getId());
    if(null != Group.getStatus()&&0 == Group.getStatus()){//班组退场
      LogHelper.setContent(LogOperateType.LABOL_GROUP_EXIT_PROJECT,g.getName());
    }else{
      LogHelper.setContent(LogOperateType.LABOL_GROUP_IN_PROJECT,g.getName());
    }
    groupService.updateStatus(Group);
    return RestBuilders.successBuilder().build();
  }

  /**
   * @Description: 根据id查询班组详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("{id}")
  @ApiOperation("根据id查询班组详情")
  public RestMessage findById(@PathVariable("id")String id) {
    Assert.notNull(id,"id不能为空");
    Group Group = groupService.getById(id);
    return RestBuilders.successBuilder().data(Group).build();
  }

  /**
   * @Description: 根据条件，分页(不分页)查询
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @PostMapping("list")
  @ApiOperation("根据条件，分页(不分页)查询")
  public RestMessage queryListByPage(@RequestBody RequestModel<GroupDTO> requestModel){
    Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
    Assert.notNull(requestModel.getPage(), "page 不能为空");
    IPage<GroupDTO> record =  groupService.queryListByPage(requestModel);
    return RestBuilders.successBuilder().data(record).build();
  }

  /**
   * 分包单位班组树形数据
   *
   * @param laborCompanyGroupVo 条件对象vo
   * @return 统一出参
   */
  @PostMapping("/subOrgGroupTree")
  @ApiOperation("分包单位班组树形")
  public RestMessage subOrgGroupTree(@RequestBody LaborCompanyGroupVo laborCompanyGroupVo) {
    return groupService.subOrgGroupTree(laborCompanyGroupVo);
  }

  /**
   * 批量导入班组
   * type = 1 为覆盖
   */
  @PostMapping("import")
  @ApiOperation("批量导入")
  public RestMessage importExcel(@NotNull @RequestPart("file") MultipartFile file,Integer type)throws Exception {
    //获取当前时间的时间
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    String key = "group:"+formatter.format(calendar.getTime());
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    AsyncUtil.submitTask(key,() ->{
      ExcelResultDTO resultDTO;
      try {
        resultDTO = groupService.importExcel(file,tenantId, type);
      } catch (Exception e) {
        throw new BusinessException(e.getMessage());
      }
      return resultDTO;
    });
    return RestBuilders.successBuilder().data(key).build();
  }

  /**
   * @Description: 下载模板
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @GetMapping("exportTemplate")
  @ApiOperation("下载模板")
  public void exportTemplate(HttpServletRequest request, HttpServletResponse response) {
    String title = "班组";
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
          .getOutputStream(request, response, fileName);
      String keyValue = "参建单位(必填*):companyName,班组(必填*):name,通行权限(必填*):serviceArea";
      ExcelTools.exportExcel(outputStream, keyValue, GroupDTO.creatExcel(), ExcelConstant.XLSX,title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常");
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！");
    }
  }

}

